/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.heathrow.auth;

import cz.muni.fi.heathrowapi.UserService;
import cz.muni.fi.heathrowapi.dto.UserDTO;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

/**
 *
 * @author Ufonzak
 */
public class AuthManager implements AuthenticationProvider
{
    private UserService userService;
    
    public void setUserService(UserService userService)
    {
        this.userService = userService;
    }

    static final Logger log = Logger.getLogger(AuthManager.class.getName());

    @Override
    public Authentication authenticate(Authentication authentication)
            throws AuthenticationException
    {
        UserDTO user = null;
        try{
            user = userService.get(authentication.getName());
        } catch(Exception ex){
            return null;
        } 
        
        if (!userService.checkPassword(user, authentication.getCredentials().toString()))
            return null;
        
        List<GrantedAuthority> authorities = new ArrayList<>();

        for(String role : user.getRoles()){
            authorities.add(new SimpleGrantedAuthority(role));
        }
        
        return new UsernamePasswordAuthenticationToken(authentication.getName(),
                authentication.getCredentials(),
                authorities);
    }


    @Override
    public boolean supports(Class<? extends Object> authentication)
    {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);

    }
}
